package com.ruoyi.common.core.utils;


import cn.hutool.core.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 常规工具类
 * @author lishaohui
 * @since 2021/5/26
 */
public class GeneralUtils {
    /**
     * 手机号码校验
     */
    public static class PhoneUtils {

        // 用于匹配手机号码
        public static final String REGEX_MOBILE_PHONE = "^0?1[34578]\\d{9}$";
        // 用于匹配固定电话号码
        public static final String REGEX_FIXED_PHONE = "^(010|02\\d|0[3-9]\\d{2})?\\d{6,8}$";
        // 用于获取固定电话中的区号
        public static final String REGEX_ZIPCODE = "^(010|02\\d|0[3-9]\\d{2})\\d{6,8}$";

        public static final Pattern PATTERN_MOBILE_PHONE;
        public static final Pattern PATTERN_FIXED_PHONE;
        public static final Pattern PATTERN_ZIPCODE;

        static {
            PATTERN_MOBILE_PHONE = Pattern.compile(REGEX_MOBILE_PHONE);
            PATTERN_FIXED_PHONE = Pattern.compile(REGEX_FIXED_PHONE);
            PATTERN_ZIPCODE = Pattern.compile(REGEX_ZIPCODE);
        }

        /**
         * 判断是否为移动手机号码
         *
         * @param phoneNumber 手机号码
         * @return boolean 结果
         */
        public static boolean isMobilePhone(String phoneNumber) {
            return PATTERN_MOBILE_PHONE.matcher(phoneNumber).matches();
        }

        /**
         * 判断是否为固定电话号码
         *
         * @param fixedTelephoneNumber 固定电话号码
         * @return boolean 结果
         */
        public static boolean isFixedPhone(String fixedTelephoneNumber) {
            if (StringUtils.isEmpty(fixedTelephoneNumber)) {
                return false;
            }
            return PATTERN_FIXED_PHONE.matcher(fixedTelephoneNumber.contains(StrUtil.DASHED)
                    ? fixedTelephoneNumber.replace(StrUtil.DASHED, StrUtil.EMPTY)
                    : fixedTelephoneNumber).matches();
        }

        /**
         * 获取固定号码号码中的区号
         *
         * @param fixedTelephoneNumber 固定电话号码
         * @return String 区号
         */
        public static String getZipFromHomephone(String fixedTelephoneNumber) {
            Matcher matcher = PATTERN_ZIPCODE.matcher(fixedTelephoneNumber);
            return matcher.find() ? matcher.group() : null;
        }

    }
}
